import { model } from '@/ts/base';
import { DataProvider } from '.';
import { IFile, ITarget, XObject } from '..';
import { IBelong } from '../target/base/belong';
import { Xbase } from '@/ts/base/schema';

/** 主页方法提供者 */
export class HomeProvider {
  private userId: string;
  private data: DataProvider;
  private cacheObj: XObject<Xbase>;
  private homeConfig: model.HomeConfig;
  constructor(_data: DataProvider) {
    this.data = _data;
    this.userId = _data.user!.id;
    this.cacheObj = _data.user!.cacheObj;
    this.homeConfig = { lastSpaceId: this.userId };
  }
  get isUser(): boolean {
    return this.current.id === this.userId;
  }
  get spaces(): IBelong[] {
    return [this.data.user!.user, ...this.data.user!.companys];
  }
  get current(): IBelong {
    return (
      this.spaces.find((i) => i.id === this.homeConfig.lastSpaceId) ?? this.data.user!
    );
  }
  commentsFlag(belong?: IBelong): string {
    belong = belong ?? this.current;
    return belong.id === this.userId ? '_commons' : `_${belong.id}commons`;
  }
  targets(belong?: IBelong): ITarget[] {
    belong = belong ?? this.current;
    return belong.id === this.userId ? this.data.targets : belong.targets;
  }
  switchSpace(space: IBelong) {
    this.homeConfig.lastSpaceId = space.id;
    this.cacheObj.set('homeConfig', this.homeConfig);
  }
  async loadConfig(): Promise<void> {
    var cache = await this.cacheObj.get<model.HomeConfig>('homeConfig');
    if (cache) {
      this.homeConfig = cache;
    }
  }
  async loadCommons(belong?: IBelong): Promise<IFile[]> {
    const files: IFile[] = [];
    belong = belong ?? this.current;
    for (const item of belong.commons) {
      const target = this.targets(belong).find(
        (i) => i.id === item.targetId && i.spaceId === item.spaceId,
      );
      if (target) {
        const file = await target.directory.searchComment(item);
        if (file) {
          if (file.groupTags.includes('已删除')) {
            console.log(item);
            belong.updateCommon(item, false);
          } else {
            files.push(file);
          }
        }
      }
    }
    return files;
  }
}
